package reflects

import (
	"errors"
	"reflect"
)

// IterateArrayOrSlice 使用反射遍历数组或切片
func IterateArrayOrSlice(entity any) (values []any, err error) {
	val := reflect.ValueOf(entity)
	for val.Kind() == reflect.Pointer {
		val = val.Elem()
	}
	kind := val.Kind()
	if kind != reflect.Array && kind != reflect.Slice {
		err = errors.New("不是数组或者切片 也不是数组和切片的指针")
		return
	}
	values = make([]any, 0, val.Len())
	for i := 0; i < val.Len(); i++ {
		ele := val.Index(i)
		values = append(values, ele.Interface())
	}
	return
}

// IterateMap 使用反射遍历 Map
func IterateMap(entity any) (keys []any, values []any, err error) {
	val := reflect.ValueOf(entity)
	for val.Kind() == reflect.Pointer {
		val = val.Elem()
	}
	kind := val.Kind()
	if kind != reflect.Map {
		err = errors.New("不是map 也不是map的指针")
		return
	}
	keys = make([]any, 0, val.Len())
	values = make([]any, 0, val.Len())
	mapKeys := val.MapKeys()
	for _, key := range mapKeys {
		keys = append(keys, key.Interface())
		values = append(values, val.MapIndex(key).Interface())
	}
	// 第二种遍历方式
	//iter := val.MapRange()
	//for iter.Next() {
	//	keys = append(keys, iter.Key().Interface())
	//	values = append(values, iter.Value().Interface())
	//}
	return
}
